<!-- 订单 -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>Order</title>
    <link rel="stylesheet" href="../../layui/css/layui.css">
    <!-- 样式 -->
    <link rel="stylesheet" href="../../css/style.css" />
    <!-- 主题（主要颜色设置） -->
    <link rel="stylesheet" href="../../css/theme.css" />
    <!-- 通用的css -->
    <link rel="stylesheet" href="../../css/common.css" />
</head>
<style>
    .navbar {
        background-color: #333;
        display: flex;
        justify-content: space-around; /* 使链接均匀分布 */
        align-items: center;
        /*position: fixed; !* 固定在顶部 *!*/
        width: 100%;
        top: 0;
        left: 0;
        z-index: 1000;
        padding: 14px 0;
    }

    .navbar a {
        color: white;
        text-align: center;
        padding: 14px 20px;
        text-decoration: none;
        flex: 1; /* 使每个链接占据相同的宽度 */
        font-size: 16px; /* 设置固定的字体大小 */
    }

    .navbar a:hover {
        background-color: #ddd;
        color: black;
    }
    #swiper {
        overflow: hidden;
    }
    #swiper .layui-carousel-ind li {
        width: 16px;
        height: 4px;
        border-width: 0;
        border-style: solid;
        border-color: rgba(0,0,0,.3);
        border-radius: 0px;
        background-color: rgba(255, 255, 255, 1);
        box-shadow: 0 0 0px rgba(255,0,0,.8);
    }
    #swiper .layui-carousel-ind li.layui-this {
        width: 16px;
        height: 4px;
        border-width: 0;
        border-style: solid;
        border-color: rgba(0,0,0,.3);
        border-radius: 0px;
        background-color: rgba(0, 85, 119, 1);
        box-shadow: 0 0 0px rgba(0, 85, 119, 1);
    }

    .index-title {
        text-align: center;
        box-sizing: border-box;
        width: 980px;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
    }

    .layui-laypage .layui-laypage-count {
        padding: 0 10px;
    }
    .layui-laypage .layui-laypage-skip {
        padding-left: 10px;
    }
</style>
<body style="background: #EEEEEE;">

<div id="app">
    <div class="navbar">
        <<a href="http://101.200.235.124:8080/shopNest/front/pages/shop-order/list2.html">order process</a>


        <a href="http://101.200.235.124:8080/shopNest/front/pages/behind/manage.html">Management Station</a>

    </div>


    <!-- 标题 -->
    <div class="index-title" :style='{"padding":"10px","boxShadow":"0 0 0px rgba(255,0,0,.8)","margin":"10px auto","borderColor":"rgba(0,0,0,.3)","backgroundColor":"rgba(252, 239, 232, 1)","color":"rgba(74, 66, 102, 1)","borderRadius":"4px","borderWidth":"0","fontSize":"28px","borderStyle":"solid","height":"80px"}'>
        <span>USER / ORDER</span><span>User Order</span>
    </div>
    <!-- 标题 -->

    <div class="center-container" style="width: 1024px;">
        <!-- 个人中心菜单 config.js-->
        <!-- <div class="left-container">
            <ul class="layui-nav layui-nav-tree">
                <li v-for="(item,index) in centerMenu" v-bind:key="index" class="layui-nav-item" :class="item.url=='../order/list.html'?'layui-this':''">
                    <a :href="'javascript:jump(\''+item.url+'\')'">{{item.name}}</a>
                </li>
            </ul>
        </div> -->
        <!-- 个人中心菜单 -->
        <div class="right-container" style="padding-top: 0;">
            <div class="layui-tab layui-tab-brief" lay-filter="docDemoTabBrief">
                <ul class="layui-tab-title">
                    <li @click="pageList('unpaid')" class="layui-this">unpaid</li>
                    <li @click="pageList('paid')">paid</li>
                    <li @click="pageList('sent out')">sent out</li>
                    <li @click="pageList('completed')">completed</li>
                    <li @click="pageList('refunded')">refunded</li>
                    <li @click="pageList('cancel')">cancel</li>
                    <li @click="pageList('dashboard')">dashboard</li>
                </ul>

                <div v-if="status != 'dashboard'" :style='{"display": "flex","justify-content": "center","padding":"20px"}'>

                    <div class="item-list">
                        <input type="date" ref="searchAddtime"
                               :style='{"boxShadow":"0 0 6px rgba(255,0,0,0)","borderColor":"rgba(102, 93, 93, 1)","backgroundColor":"#fff","color":"#333","borderRadius":"6px","textAlign":"center","borderWidth":"1px","width":"150px","fontSize":"14px","borderStyle":"solid","height":"40px"}'
                               autocomplete="off">
                    </div>
                    <button @click="searchData" :style='{"padding":"0 15px","boxShadow":"0 0 8px rgba(0,0,0,0)","margin":"0 0 0 10px","borderColor":"#FF007F","backgroundColor":"rgba(255, 102, 178, 1)","color":"#fff","borderRadius":"6px","borderWidth":"0","width":"auto","fontSize":"18px","borderStyle":"solid","height":"40px"}'
                            id="btn-search" type="button" class="layui-btn layui-btn-normal">
                        <i v-if="true" class="layui-icon layui-icon-search"></i> search
                    </button>
                </div>

                <div v-if="status === 'dashboard'" class="layui-form">
                    <div :style='{"display": "flex","justify-content": "center","padding":"20px"}'>
                        <div class="item-list">
                            <label>Start Date:</label>
                            <input type="date" ref="dashboardStartDate"
                                   :style='{"boxShadow":"0 0 6px rgba(255,0,0,0)","borderColor":"rgba(102, 93, 93, 1)","backgroundColor":"#fff","color":"#333","borderRadius":"6px","textAlign":"center","borderWidth":"1px","width":"150px","fontSize":"14px","borderStyle":"solid","height":"40px", "margin-right": "10px"}'
                                   autocomplete="off">
                        </div>
                        <div class="item-list">
                            <label>End Date:</label>
                            <input type="date" ref="dashboardEndDate"
                                   :style='{"boxShadow":"0 0 6px rgba(255,0,0,0)","borderColor":"rgba(102, 93, 93, 1)","backgroundColor":"#fff","color":"#333","borderRadius":"6px","textAlign":"center","borderWidth":"1px","width":"150px","fontSize":"14px","borderStyle":"solid","height":"40px"}'
                                   autocomplete="off">
                        </div>
                        <button @click="loadDashboardData" :style='{"padding":"0 15px","boxShadow":"0 0 8px rgba(0,0,0,0)","margin":"0 0 0 10px","borderColor":"#FF007F","backgroundColor":"rgba(255, 102, 178, 1)","color":"#fff","borderRadius":"6px","borderWidth":"0","width":"auto","fontSize":"18px","borderStyle":"solid","height":"40px"}'
                                id="btn-dashboard-search" type="button" class="layui-btn layui-btn-normal">
                            <i v-if="true" class="layui-icon layui-icon-search"></i> display
                        </button>
                    </div>
                </div>

            </div>

            <div  v-if="status != 'dashboard'">

                <div class="order-stats" :style='{"margin":"0 auto","textAlign":"center","padding":"15px 0","fontSize":"16px","fontWeight":"bold","color":"#333"}'>
                    <div :style='{"display":"flex","justify-content":"center","gap":"40px","align-items":"center"}'>
                        <div>
                            <div>Orders Total</div>
                            <div style="font-size:20px;color:#FF5722;">{{ orderStats.totalCount }}</div>
                        </div>
                        <div>
                            <div>Total Money</div>
                            <div style="font-size:20px;color:#2196F3;">{{ orderStats.totalPrice }} RMB</div>
                        </div>
                    </div>
                </div>

                <div class="layui-tab-content">
                    <table class="layui-table" lay-skin="nob">
                        <thead>
                        <tr>
                            <th>Order ID</th>
                            <th>Item</th>
                            <th>Prcie</th>
                            <th>Amount</th>
                            <th>Total Price</th>
                            <th>Address</th>
                            <th>Phone</th>
                            <th>Username</th>
                            <th>AddTime</th>
                            <th style="min-width:150px">Operate</th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr v-for="(item,index) in dataList" v-bind:key="index">
                            <td style="width: 50px;">
                                {{item.orderid}}
                            </td>
                            <td style="display: flex;text-align: left;width: 250px;">
                                <img :src="item.picture" style="width: 100px;height: 100px;object-fit: cover;">
                                <div style="margin-left: 10px;margin-top: 10px;">
                                    {{item.goodname}}
                                </div>
                            </td>
                            <td style="width: 100px;">{{item.price}} RMB</td>
                            <td style="width: 50px;">
                                {{item.buynumber}}
                            </td>
                            <td style="width: 100px;">{{(item.price*item.buynumber).toFixed(2)}} RMB</td>
                            <td style="width: 200px;">
                                {{item.address}}
                            </td>
                            <td style="width: 150px;"> <!-- 新增列内容 -->
                                {{item.phone}}
                            </td>
                            <td style="width: 150px;"> <!-- 新增列内容 -->
                                {{item.yonghuming}}
                            </td>
                            <td style="width: 150px;"> <!-- 新增列内容 -->
                                {{item.addtime}}
                            </td>
                            <td style="width: 100px;">

                                </button>
                                <button v-if="item.status=='paid'" @click="refund(item)" type="button" class="layui-btn layui-btn-sm layui-btn-radius layui-btn-warm">
                                    <i class="layui-icon">&#xe65e;</i> dispatch goods
                                </button>

                            </td>
                        </tr>
                        </tbody>
                    </table>
                    <div class="pager" id="pager" :style="{textAlign:1==1?'left':1==2?'center':'right'}"></div>
                </div>
            </div>
        </div>
    </div>
</div>
</div>

<div v-if="status === 'dashboard'" style="margin: 20px auto; max-width: 1200px;">
    <div id="dashboardChart" style="width: 100%; height: 500px;"></div>
</div>

<!-- layui -->
<script src="../../layui/layui.js"></script>
<!-- vue -->
<script src="../../js/vue.js"></script>
<!-- 组件配置信息 -->
<script src="../../js/config.js"></script>
<!-- 扩展插件配置信息 -->
<script src="../../modules/config.js"></script>
<!-- 工具方法 -->
<script src="../../js/utils.js"></script>
<!-- 校验格式工具类 -->
<script src="../../js/validate.js"></script>
<script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
<script>
    var vue = new Vue({
        el: '#app',
        data: {
            // 轮播图
            swiperList: [{
                img: '../../img/banner.jpg'
            }],
            dataList: [],
            centerMenu: centerMenu,
            status: 'unpaid',
            addtime: null,
            limit: 10,
            user: {},
            orderStats: {
                totalCount: 0,
                totalPrice: 0
            },
            statusList: ['unpaid', 'paid', 'sent out', 'completed', 'refunded', 'cancel'],
            dashboardStatsMap: null,
            myChartInstance: null,
        },
        methods: {
            searchData() {
                this.addtime = this.$refs.searchAddtime.value;
                console.log('searchAddtime', this.addtime, '????????');
                this.pageList(this.status);
            },
            jump(url) {
                jump(url)
            },
            pageList(status) {
                // 如果当前不是 dashboard，并且存在图表实例，销毁它
                if (status !== 'dashboard' && this.myChartInstance) {
                    this.myChartInstance.dispose();
                    this.myChartInstance = null;
                }
                this.status = status;
                console.log(layui);

                // 第一个表数据请求
                layui.http.request('orders/list2', 'get', {
                    status: vue.status, // 根据状态过滤订单
                    searchAddtime : this.addtime
                }, function(res1) {
                    // 第二个表数据请求
                    layui.http.request('yonghu/list', 'get', {
                        status: vue.status // 根据状态过滤订单
                    }, function(res2) {
                        // 构建一个由id映射到yonghuming的映射表
                        let yonghumingMap = {};
                        res2.data.list.forEach(item => {
                            yonghumingMap[item.id] = item.xingming; // 以id为键，yonghuming为值
                        });

                        // 在第一个表数据中根据userid查找对应的id，从而获取yonghuming并添加
                        let combinedData = res1.data.list.map(order => {
                            // 通过第一个表的userid，在第二个表的yonghumingMap中找到对应的yonghuming
                            let yonghuming = yonghumingMap[order.userid]; // 使用userid在映射表中查找yonghuming
                            return {
                                ...order,  // 保留第一个表的原始数据
                                yonghuming: yonghuming || '未知' // 如果找不到对应的yonghuming，则设置为'未知'
                            };
                        });

                        // 将合并的数据赋值给dataList
                        vue.dataList = combinedData;
                        vue.orderStats = res1.orderStats;

                        // 分页
                        layui.laypage.render({
                            elem: 'pager',
                            count: res1.data.total, // 总数为第一个表的数据总数
                            limit: this.limit,
                            jump: function(obj, first) {
                                if (!first) {
                                    layui.http.request('orders/list2', 'get', {
                                        page: obj.curr,
                                        limit: obj.limit,
                                        userid: localStorage.getItem('userid'),
                                        status: this.status,
                                        searchAddtime : this.addtime
                                    }, function(res) {
                                        vue.dataList = res.data.list;
                                        vue.orderStats = res.orderStats;
                                    });
                                }
                            }
                        });
                    });
                });
            },
            // 支付
            pay(item) {
                // 获取商品详情信息
                layui.http.request(`${item.tablename}/info/${item.goodid}`, 'get', {}, (res) => {
                    // 商品信息
                    let data = res.data;
                    // 用户当前用户信息
                    let table = localStorage.getItem("userTable");
                    layui.http.request(`${table}/session`, 'get', {}, function(data) {
                        this.user = data.data;
                        // 判断余额是否充足
                        if (this.user.money < this.totalPrice) {
                            layui.layer.msg('Your balance is insufficient Please recharge your account first', {
                                time: 2000,
                                icon: 5
                            });
                            return
                        }
                        // 如果该商品存在积分
                        if (data.jifen) {
                            this.user.jifen = Number(this.user.jifen) + Number(data.jifen * item.buynumber);
                        }
                        this.user.money = this.user.money - this.totalPrice;
                        // 更新用户余额
                        layui.http.requestJson(`${localStorage.getItem("userTable")}/update`, 'post', this.user, (res) => {
                            item.status = 'paid'
                            layui.http.requestJson(`orders/update`, 'post', item, (res) => {
                                layui.layer.msg('Successfully purchased', {
                                    time: 2000,
                                    icon: 6
                                }, function() {
                                    window.location.reload();
                                });
                            });
                        });
                    });
                });
            },
            // 退款
            refund(item) {
                // 获取商品详情信息
                layui.http.request(`${item.tablename}/info/${item.goodid}`, 'get', {}, (res) => {
                    // 商品信息
                    let data = res.data;
                    // 用户当前用户信息
                    let table = localStorage.getItem("userTable");
                    layui.http.request(`${table}/session`, 'get', {}, function(data) {
                        this.user = data.data;
                        // 如果该商品存在积分

                        // 更新用户余额
                        layui.http.requestJson(`${localStorage.getItem("userTable")}/update`, 'post', this.user, (res) => {
                            item.status = 'sent out'
                            layui.http.requestJson(`orders/update`, 'post', item, (res) => {
                                layui.layer.msg('The goods are about to be dispatched', {
                                    time: 2000,
                                    icon: 6
                                }, function() {
                                    window.location.reload();
                                });
                            });
                        });
                    });
                });
            },
            confirm(item){
                item.status = 'completed'
                layui.http.requestJson(`orders/update`, 'post', item, (res) => {
                    layui.layer.msg('The confirmation of receipt of the goods was successful', {
                        time: 2000,
                        icon: 6
                    }, function() {
                        window.location.reload();
                    });
                });
            },
            cancel(item){
                item.status = 'cancel'
                layui.http.requestJson(`orders/update`, 'post', item, (res) => {
                    layui.layer.msg('The order has been successfully cancelled', {
                        time: 2000,
                        icon: 6
                    }, function() {
                        window.location.reload();
                    });
                });
            },

            loadDashboardData() {
                const startDate = vue.$refs.dashboardStartDate.value;
                const endDate = vue.$refs.dashboardEndDate.value;

                if (!startDate || !endDate) {
                    layui.layer.msg('请选择起始和结束日期');
                    return;
                }

                // 所有要查询的状态
                const statusList = ['unpaid', 'paid', 'sent out', 'completed', 'refunded', 'cancel'];
                const start = new Date(startDate);
                const end = new Date(endDate);

                let currentDate = new Date(start);
                const dateList = [];

                // 存储所有日期+状态组合是否已完成请求
                const dateStatusMap = {};

                // 收集所有日期并初始化 map
                while (currentDate <= end) {
                    const year = currentDate.getFullYear();
                    const month = String(currentDate.getMonth() + 1).padStart(2, '0');
                    const day = String(currentDate.getDate()).padStart(2, '0');
                    const dateStr = `${year}-${month}-${day}`;
                    dateList.push(dateStr);

                    // 初始化每个日期下的所有 status 请求标记
                    dateStatusMap[dateStr] = {};
                    statusList.forEach(status => {
                        dateStatusMap[dateStr][status] = false;
                    });

                    currentDate.setDate(currentDate.getDate() + 1);
                }

                // 每个日期 + 每个 status 发起请求
                dateList.forEach(dateStr => {
                    statusList.forEach(status => {
                        layui.http.request('orders/list2', 'get', {
                            searchAddtime: dateStr,
                            status: status
                        }, function(res) {
                            const count = res.data.list.length;
                            const price = res.data.list.reduce((sum, item) => sum + (item.price * item.buynumber), 0);

                            // 更新对应日期的状态数据
                            if (!vue.dashboardStatsMap) vue.dashboardStatsMap = {};
                            if (!vue.dashboardStatsMap[dateStr]) vue.dashboardStatsMap[dateStr] = {};

                            vue.dashboardStatsMap[dateStr][status] = {
                                count: count,
                                price: price.toFixed(2)
                            };

                            // 标记此 status 已加载完成
                            dateStatusMap[dateStr][status] = true;

                            // 判断是否全部完成
                            const allLoaded = dateList.every(date => {
                                return statusList.every(status => dateStatusMap[date][status]);
                            });

                            if (allLoaded) {
                                // 全部加载完成，开始渲染图表
                                vue.$nextTick(() => {
                                    vue.renderDashboardChart(); // 渲染图表
                                });
                            }
                        });
                    });
                });

                // 初始化 dashboardStatsMap
                vue.dashboardStatsMap = {};
            },
            renderDashboardChart() {
                const chartDom = document.getElementById('dashboardChart');
                if (!chartDom) return;

                const myChart = echarts.init(chartDom);
                vue.myChartInstance = myChart; // 保存实例以便销毁

                // 提取所有日期并排序
                const dates = Object.keys(vue.dashboardStatsMap).sort();

                // 构建 series 数据
                const series = [];

                this.statusList.forEach(status => {
                    // 柱状图数据 - 订单数量
                    series.push({
                        name: `${status} - Orders`,
                        type: 'bar',
                        stack: status,
                        barGap: '0%',
                        legendIcon: 'rect', // 方形图例
                        itemStyle: { opacity: 0.8 },
                        data: dates.map(date => {
                            const item = vue.dashboardStatsMap[date]?.[status];
                            return item ? item.count : 0;
                        })
                    });

                    // 折线图数据 - 总金额
                    series.push({
                        name: `${status} - Money`,
                        type: 'line',
                        yAxisIndex: 1,
                        smooth: true,
                        symbol: 'circle',
                        symbolSize: 6,
                        lineStyle: { width: 2 },
                        legendIcon: 'roundRect', // 圆角矩形图例
                        data: dates.map(date => {
                            const item = vue.dashboardStatsMap[date]?.[status];
                            return item ? parseFloat(item.price) : 0;
                        })
                    });
                });

                // 图例分两行显示
                const legendData1 = this.statusList.map(status => `${status} - Orders`);
                const legendData2 = this.statusList.map(status => `${status} - Money`);

                const option = {
                    tooltip: {
                        trigger: 'axis',
                        formatter: (params) => {
                            let res = `<strong>${params[0].name}</strong><br>`;
                            params.forEach(p => {
                                const [type, field] = p.seriesName.split(' - ');
                                res += `${p.marker} ${p.seriesName}: <strong>${p.value}</strong><br>`;
                            });
                            return res;
                        }
                    },
                    legend: [
                        {
                            data: legendData1,
                            top: 40,
                            left: 'center'
                        },
                        {
                            data: legendData2,
                            top: 70,
                            left: 'center'
                        }
                    ],
                    grid: {
                        left: 80,
                        right: 80,
                        bottom: 60,
                        top: 120,
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        data: dates
                    },
                    yAxis: [
                        {
                            type: 'value',
                            name: 'Orders Num'
                        },
                        {
                            type: 'value',
                            name: 'Total Money(RMB)'
                        }
                    ],
                    series: series
                };

                myChart.setOption(option);
            }
        }//method
    })

    layui.use(['layer', 'element', 'carousel', 'http', 'jquery', 'form', 'laypage'], function() {
        var layer = layui.layer;
        var element = layui.element;
        var carousel = layui.carousel;
        var http = layui.http;
        var jquery = layui.jquery;
        var laypage = layui.laypage;
        var form = layui.form;
        var userMap = {};
        var limit = 10;

        // 获取轮播图 数据
        http.request('config/list', 'get', {
            page: 1,
            limit: 5
        }, function(res) {
            if (res.data.list.length > 0) {
                var swiperItemHtml = '';
                for (let item of res.data.list) {
                    if (item.name.indexOf('picture') >= 0 && item.value && item.value != "" && item.value != null) {
                        swiperItemHtml +=
                            '<div>' +
                            '<img class="swiper-item" style="width: 100%;height: 100%;object-fit:cover;" src="' + item.value + '">' +
                            '</div>';
                    }
                }
                jquery('#swiper-item').html(swiperItemHtml);
                // 轮播图
                vue.$nextTick(() => {
                    carousel.render({
                        elem: '#swiper',
                        width: '100%',
                        height: '600px',
                        arrow: 'hover',
                        anim: 'default',
                        autoplay: 'true',
                        interval: '3000',
                        indicator: 'inside'
                    });

                })
            }
        });
        http.request('yonghu/list', 'get', {}, function(res) {
            {
                // 遍历用户数据，将 id 和 xingming 存储到 userMap 中
                res.data.list.forEach(function(user) {
                    console.error('接口请求失败：' + res.msg);
                    userMap[user.id] = user.xingming;
                });
                console.log('userMap:', userMap);
            }

        });
        // 获取列表数据
        http.request('orders/list2', 'get', {
            status: vue.status, // 可以根据状态过滤订单
            searchAddtime : this.addtime
        }, function(res) {
            res.data.list.forEach(function(item) {
                console.error('接口请求失败：' + res.msg);
                item.xingming = userMap[item.userid]; // 将对应的 xingming 存储到 item 中

            });
            // 更新 Vue 的 dataList 数据
            vue.dataList = res.data.list;
            vue.orderStats = res.orderStats;



            // 分页
            laypage.render({
                elem: 'pager',
                count: res.data.total,
                limit: vue.limit,
                groups: 3,
                layout: ["prev","page","next"],
                theme: '#065279',
                jump: function(obj, first) {
                    //首次不执行
                    if (!first) {
                        http.request('orders/list2', 'get', {
                            page: obj.curr,
                            limit: obj.limit,
                            userid: obj.userid,
                            status: vue.status,
                            searchAddtime : this.addtime
                        }, function(res) {
                            vue.dataList = res.data.list
                            vue.orderStats = res.orderStats
                        })
                    }
                }
            });
        })

    });
</script>
</body>
</html>